package cn.wyz.org.service.impl;

import cn.wyz.basic.service.impl.BaseServiceImpl;
import cn.wyz.basic.util.MD5Utils;
import cn.wyz.basic.util.StrUtils;
import cn.wyz.org.domain.Employee;
import cn.wyz.org.mapper.EmployeeMapper;
import cn.wyz.org.service.IEmployeeService;
import cn.wyz.user.domain.Logininfo;
import cn.wyz.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;
    //1.基础的CRUD实现通过继承BaseServiceImpl 得到

    //2.特殊的接口实现在这里自己写

    /**
     * 员工新增时要级联新增logininfo
     * @param employee
     */
    @Override
    public void insert(Employee employee){
        initEmployee(employee);
        //级联设置并保存,在logininfoMapper.insert中返回自增id
        Logininfo logininfo = employee2Logininfo(employee);
        logininfoMapper.insert(logininfo);
        //回设employee表中Logininfo_id属性
        employee.setLogininfo_id(logininfo.getId());
        employeeMapper.insert(employee);
    }

    /**
     * 修改时要级联修改
     * @param employee
     */
    @Override
    public void update(Employee employee) {
        Logininfo logininfo = logininfoMapper.selectById(employee.getLogininfo_id());
        BeanUtils.copyProperties(employee,logininfo);
        employeeMapper.update(employee);
    }

    /**
     * 删除
     */
    @Override
    public void deleteById(Long id) {
        Employee employee = employeeMapper.selectById(id);
        logininfoMapper.deleteById(employee.getId());
        employeeMapper.deleteById(id);
    }

    /**
     * 数据拷贝
     * @param employee
     * @return
     */
    private Logininfo employee2Logininfo(Employee employee) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee,logininfo);
        logininfo.setType(0);
        return logininfo;
    }

    /**
     * 创建Employee时进行初始化密码与盐值
     * @param employee
     */
    private void initEmployee(Employee employee) {
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = MD5Utils.encrypByMd5(salt + employee.getPassword());
        employee.setSalt(salt);
        employee.setPassword(md5Pwd);
    }

}
